#!/usr/bin/env python3
"""
VectorDB Microservice Startup Script

This script provides convenient ways to start the VectorDB microservice
with different configurations and options.
"""

import argparse
import asyncio
import os
import sys
import subprocess
from pathlib import Path

# Add the current directory to Python path
sys.path.insert(0, str(Path(__file__).parent))

def check_dependencies():
    """Check if required dependencies are installed."""
    try:
        import fastapi
        import uvicorn
        import lancedb
        import httpx
        print("✓ All required dependencies are installed")
        return True
    except ImportError as e:
        print(f"✗ Missing dependency: {e}")
        print("Please install dependencies: pip install -r requirements.txt")
        return False

def check_ollama():
    """Check if Ollama is running and has the required model."""
    try:
        import httpx
        client = httpx.Client(timeout=5.0)
        response = client.get("http://localhost:11434/api/tags")

        if response.status_code == 200:
            models = response.json().get('models', [])
            available_models = [m.get('name', '') for m in models]

            if 'qwen3-embedding:0.6b' in available_models:
                print("✓ Ollama is running and qwen3-embedding:0.6b model is available")
                return True
            else:
                print(f"✗ qwen3-embedding:0.6b model not found in Ollama")
                print(f"Available models: {available_models}")
                print("To install the model, run: ollama pull qwen3-embedding:0.6b")
                return False
        else:
            print(f"✗ Ollama health check failed: {response.status_code}")
            return False

    except Exception as e:
        print(f"✗ Cannot connect to Ollama: {e}")
        print("Please ensure Ollama is running: ollama serve")
        return False

def setup_environment():
    """Set up environment variables from .env file."""
    env_file = Path(".env")
    if env_file.exists():
        print("Loading environment variables from .env file...")
        with open(env_file) as f:
            for line in f:
                line = line.strip()
                if line and not line.startswith('#') and '=' in line:
                    key, value = line.split('=', 1)
                    key = key.strip()
                    value = value.strip().strip('"\'')
                    os.environ[key] = value
    else:
        print("No .env file found, using default configuration")

def create_directories():
    """Create necessary directories."""
    directories = [
        "data",
        "logs",
        "tests",
        "examples"
    ]

    for directory in directories:
        Path(directory).mkdir(exist_ok=True)
        print(f"✓ Created directory: {directory}")

def run_tests():
    """Run the test suite."""
    print("Running tests...")
    try:
        result = subprocess.run([sys.executable, "-m", "pytest", "tests/", "-v"],
                              capture_output=True, text=True)
        print(result.stdout)
        if result.stderr:
            print(result.stderr)
        return result.returncode == 0
    except Exception as e:
        print(f"Failed to run tests: {e}")
        return False

def run_dev_server(host="0.0.0.0", port=8000, reload=True):
    """Run the development server."""
    print(f"Starting development server on {host}:{port}")

    try:
        import uvicorn
        uvicorn.run(
            "main:create_app",
            host=host,
            port=port,
            reload=reload,
            log_level="info",
            factory=True
        )
    except KeyboardInterrupt:
        print("\nShutting down development server...")
    except Exception as e:
        print(f"Failed to start development server: {e}")
        sys.exit(1)

def run_production_server(host="0.0.0.0", port=8000, workers=1):
    """Run the production server."""
    print(f"Starting production server on {host}:{port} with {workers} workers")

    try:
        import uvicorn
        uvicorn.run(
            "main:create_app",
            host=host,
            port=port,
            workers=workers,
            log_level="info",
            factory=True
        )
    except KeyboardInterrupt:
        print("\nShutting down production server...")
    except Exception as e:
        print(f"Failed to start production server: {e}")
        sys.exit(1)

def test_embedding():
    """Test the embedding functionality."""
    print("Testing embedding functionality...")

    try:
        from core.embedding import get_embedding_service, embed_text
        import asyncio

        async def test_embed():
            service = await get_embedding_service()

            # Test health check
            health = await service.health_check()
            print(f"Provider health: {health}")

            # Test embedding
            test_text = "This is a test sentence for embedding."
            embedding = await embed_text(test_text)

            if embedding and len(embedding) > 0:
                print(f"✓ Embedding successful!")
                print(f"  Vector dimensions: {len(embedding)}")
                print(f"  First 5 values: {embedding[:5]}")
                return True
            else:
                print("✗ Embedding failed")
                return False

        return asyncio.run(test_embed())

    except Exception as e:
        print(f"✗ Embedding test failed: {e}")
        return False

def main():
    """Main function."""
    parser = argparse.ArgumentParser(
        description="VectorDB Microservice Startup Script",
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog="""
Examples:
  # Start development server
  python start.py dev

  # Start production server
  python start.py prod

  # Run tests
  python start.py test

  # Check dependencies and setup
  python start.py setup

  # Test embedding functionality
  python start.py test-embed

  # Run with custom host and port
  python start.py dev --host 127.0.0.1 --port 8080
        """
    )

    parser.add_argument(
        "command",
        choices=["dev", "prod", "test", "setup", "test-embed"],
        help="Command to run"
    )

    parser.add_argument(
        "--host",
        default="0.0.0.0",
        help="Host to bind to (default: 0.0.0.0)"
    )

    parser.add_argument(
        "--port",
        type=int,
        default=8000,
        help="Port to bind to (default: 8000)"
    )

    parser.add_argument(
        "--workers",
        type=int,
        default=1,
        help="Number of worker processes for production mode (default: 1)"
    )

    parser.add_argument(
        "--no-reload",
        action="store_true",
        help="Disable auto-reload for development mode"
    )

    args = parser.parse_args()

    print("=" * 60)
    print("VectorDB Microservice Startup Script")
    print("=" * 60)

    # Setup environment
    setup_environment()

    # Execute command
    if args.command == "setup":
        print("Running setup...")

        # Check dependencies
        if not check_dependencies():
            print("Please install missing dependencies and try again.")
            sys.exit(1)

        # Create directories
        create_directories()

        # Check Ollama
        if not check_ollama():
            print("Please ensure Ollama is running and has the required model.")
            print("1. Start Ollama: ollama serve")
            print("2. Pull model: ollama pull qwen3-embedding:0.6b")
            sys.exit(1)

        print("✓ Setup completed successfully!")
        print("You can now start the service with: python start.py dev")

    elif args.command == "test":
        print("Running tests...")
        if run_tests():
            print("✓ All tests passed!")
        else:
            print("✗ Some tests failed")
            sys.exit(1)

    elif args.command == "test-embed":
        print("Testing embedding functionality...")
        if test_embedding():
            print("✓ Embedding test passed!")
        else:
            print("✗ Embedding test failed")
            sys.exit(1)

    elif args.command == "dev":
        print("Starting in development mode...")

        # Quick checks
        if not check_dependencies():
            print("Missing dependencies. Run: pip install -r requirements.txt")
            sys.exit(1)

        create_directories()

        if not check_ollama():
            print("Warning: Ollama not available. Embedding functionality may not work.")

        run_dev_server(args.host, args.port, reload=not args.no_reload)

    elif args.command == "prod":
        print("Starting in production mode...")

        # Full setup check
        if not check_dependencies():
            print("Missing dependencies. Run: pip install -r requirements.txt")
            sys.exit(1)

        create_directories()

        if not check_ollama():
            print("Warning: Ollama not available. Embedding functionality may not work.")

        run_production_server(args.host, args.port, args.workers)


if __name__ == "__main__":
    main()